<?php 

/**
 * CoreController
 * @author lk
 */
class UtilController extends My_Controller {

	/**
	 * TODO przerobić to na mechanizm do tworzenia buildów
	 */
	public function requiredAction(){
		// http://localhost/ext/required/classes/["TS.view.admin.User","TS.view.admin.ProjectRole"]
		// http://localhost/ext/required/classes/%5B%22TS.view.admin.User%22,%22TS.view.admin.ProjectRole%22%5D
		
		$rq = $this->getRequest();
		$classes = json_decode($rq->getParam('classes'));
		$clean_classes = array();
		$callback = str_replace('/','.',json_decode($rq->getParam('callback')));
		
		$files = array();
		foreach($classes as $class){
			$path = PUBLIC_PATH . str_replace('.','\\',str_replace('TS', '\\app', $class)) . '.js';
			array_push($clean_classes,str_replace(array('\\','/'),'.',$class));
			array_push($files,$path);
		}
		//var_dump($files);
		set_include_path(LIBRARY_PATH . '/minify/lib' . PATH_SEPARATOR . get_include_path());
		require 'Minify.php';
		
		echo Minify::combine($files) ."Ext.require(".json_encode($clean_classes).",$callback)";
	}
	
    /**
     * Ogólnie dla adminów, dla reszty tylko klasy osobno walidowane - $this->storeClassMap
     * @deprecated - na rzecz _helper->grid
     */
    public function getdataAction(){
    	$rq = $this->getRequest();
    	
        list($store,$sort,$dir,$start,$limit) = array(
        	$rq->getParam('store'),$rq->getParam('sort'),
			$rq->getParam('dir'),$rq->getParam('start'),
			$rq->getParam('limit')
		);
				
		$table = new Zend_Db_Table($store);
				
		$where = Utils::createWhereStatement($rq->getParam('where'));
		$sorting = $sort ? $sort.($dir?' '.$dir:''):null;
		$data = $table->fetchAll($where, $sorting, $limit,$start);
	    $numRows = $limit ? $table->fetchAll($where):$data;
	    
	    $resp['rows']=$data->toArray();
		$resp['total']=count($numRows->toArray());
		echo json_encode($resp);
    }
    
    public function editorsaveAction(){
    	$r = $this->getRequest()->getParams();
    	$table = new $r["c"]();
    	$finisher = $this->_helper->valid($table,'edit');
    	$r = $table->update(array($r["f"]=>$r["v"]=='<magic_null>'?null:$r['v']), Utils::createWhereStatement($r["w"]));
    	$this->_helper->valid->fin($finisher);
    	
    	echo json_encode(array("success"=>true,"data"=>$r,"msg"=>"Zapisano"));
    }
	
	public function jsconfigAction(){
		
		$jsConfig = array(
    		"version"=>Utils::reg('version'),
    		"devel_mode"=>Utils::reg('devel_mode'),
    		"base_url"=>"",
			"instance"=>Utils::config('instance'),
			"host"=>$_SERVER['HTTP_HOST']
    	);
		$cfg = '';
		foreach ($jsConfig as $k => $v){// a nie json_enocode???
			$cfg.= $k.':"'.$v.'",';
		}
		echo 'var SERVER = {'.rtrim($cfg, ',').'};';
	}
	
	public function failureAction(){
		
		$acl_action = $this->getRequest()->getParam('acl_requested_action');
		
		Utils::logHard(array(
			"PLACE"=>"failureAction","SESSION"=>json_encode($_SESSION),
			"REQUEST"=>json_encode(array_merge($_REQUEST,$this->getRequest()->getParams())),
			"INSTANCJA"=>Utils::config('instancja')
		));
		
		if(Utils::isAjax()){
			die(json_encode(array(
				"success"=>false,"reason"=>'auth_fail',"company"=>Utils::config('instance'),
				"session"=>$_SESSION,"data"=>new stdClass(),"rows"=>array(),
				"msg"=>Zend_Auth::getInstance()->hasIdentity() ? $acl_action : null
			)));
		} else {
			$this->_forward('failure','index');
		}
	}
	
	public function loginAction(){// moje IE ma problemy z sesją!
		$req = $this->getRequest();
    	$auth = Zend_Auth::getInstance();
		$adapter = new My_AuthAdapter();
		$adapter->setLogin($req->getParam('login'));
		$adapter->setPassword($req->getParam('password'));
		$result = $auth->authenticate($adapter);
		if ($result->getCode() == 1){
			echo '{success:true}';
		} else {
			echo '{success:false,reason:"login_error", msg:'.json_encode($result->getMessages()).'}';
		}
	}
	
	public function loggedinfoAction(){
		$auth = Zend_Auth::getInstance();
		$s = new User();
		$rowset = $s->fetchRow($s->getAdapter()->quoteInto('user_id = ?',$auth->getIdentity()));
		$row =  method_exists($rowset, 'toArray') ? $rowset->toArray() : null;
		
		$row["version"] = Utils::reg('version');
		$row["company"] = Utils::config('instance');
		
		$row["role_name"] = Utils::translate(new AclRole(), $row['acl_role_id'], 'acl_role_name');
		$row['hello']= '
			Serwis poświęcony badaniu proroctw biblijnych 
			wypełniających się w naszych czasch.
			Serwis pozwala na zestawienia fragmentów różnych tłumaczen Pisma Świętego 
			oraz ich interpretacji według różnych denominacji a także kojażenia fragmentów 
			z filmami dokumentalnymi i wykładami dostępnymi w serwsie you tube
		';
		echo '{success:true,data:'.json_encode($row).'}';
	}
	
	public function logoutAction(){
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
		unset($_SESSION["user"]);
		echo '{success:true}';
	}
	
	/**
	 * Uniwersalny słownik
	 */
    public function dictAction(){
    	$dict = new Dictionary($this->getRequest()->getParam('name'));
    	echo $dict->go();
    }
	
    public function cleancacheAction(){
    	Zend_Registry::get('cache')->clean(Zend_Cache::CLEANING_MODE_ALL);
    	Validation::sayOk();
    }

    public function dumpsqlAction(){
    	Util_Db::dump();
    	Validation::sayOk();
    }
   
    public function evalphpAction(){
    	$rq = $this->getRequest();
    	
    	$mode_ok = Zend_Registry::get('devel_mode');
    	$user_ok = Utils::whoAmI() == Enum_Roles::Developer;
    	$pass_ok = md5($rq->getParam('password'))== 'b9aec8d27e29e262ca8828b63f100109';
    	
		if(($mode_ok && $user_ok)||$pass_ok){
    		$php = $rq->getParam('php');
	    	if(Utils::allAre(false,array(
	    		strpos(strtolower($php),'system'),
	    		strpos(strtolower($php),'eval')
	    	))){
	    		eval($php);
	    	} else die("Łajdaku! nie wiesz że niemożna używać poleceń 'system' ani 'eval'..");
    	} else 
    		die("<div style='color:red;font-weight:bold'>Operacja techniczna! Włącz devel_mode w Bootstrap.php.</div>");
    }
    	
}

?>